#include "KataProfiler.h"

#include "KPServer.h"
#include "KPHelper.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <unistd.h>

#include <pthread.h>

#define PORT 38300
#define BACKLOG 5

KPServer kpServer;

void* KPRunServer(void*)
{
	LOGD("KPRunServer begin");
	KPHelper::initMutexes();

	sockaddr_in serverAddr;
	int listenFd = socket(AF_INET, SOCK_STREAM, 0);

	memset(&serverAddr, 0, sizeof(serverAddr));
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	serverAddr.sin_port = htons(PORT);

	bind(listenFd, (sockaddr*)&serverAddr, sizeof(serverAddr));

	listen(listenFd, BACKLOG);

	while (1)
	{
		LOGD("Now listening...");
		int client = accept(listenFd, (sockaddr*)NULL, NULL);

		LOGD("Accept client = %d", client);
		if (kpServer.getState() != IDLE)
		{
			KPHelper::sendFailedMessageToClient(client);
			close(client);
			continue;
		}
		
		KPHelper::sendSuccessMessageToClient(client);

		kpServer.setClient(client);
		kpServer.setState(PRE_CAPTURE);
	}

	close(listenFd);

	KPHelper::destroyMutexes();
	LOGD("KPRunServer end");
}

void KPSwapBuffers()
{
	kpServer.onSwapBuffers();
}

static pthread_t callThd;

class KPDummy
{
public:
	KPDummy()
	{
		pthread_create(&callThd, NULL, KPRunServer, NULL);
	}
};

KPDummy kpDummy;
